<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>index</title>
		<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
		<style type="text/css">
			img {
				margin: 10px;
			}
		</style>
	</head>
	<body>
		<div id="contain">

		</div>
		<script>
			$(function() {
				var newData = {};
				var contain;
				var nextUrl;
				//将获取到的数据根据日期放到不同的数组中
				function group(photos) {
					if (photos) {
						for (var i = 0; i < photos.length; i++) {
							var timeStr = showTime(photos[i].time);
							if (newData[timeStr]) {
								newData[timeStr].push(photos[i]);
							} else {
								newData[timeStr] = [];
								newData[timeStr].push(photos[i]);
							}
						}
					}
				}

				//将时间进行yyyy-mm-dd格式化
				function showTime(time) {
					var myTime = new Date(time);
					var day = myTime.getDate();
					var month = myTime.getMonth() + 1;
					var year = myTime.getFullYear();
					day = day < 10 ? '0' + day : day;
					month = month < 10 ? '0' + month : month;
					return year + '-' + month + '-' + day;
				}


				
				//获取并且处理现实数据
				function getJsonData(nextPageUrl) {
					if (!nextPageUrl) {
						nextPageUrl = 'http://photo-sync.herokuapp.com/photos';
					}
					contain = document.getElementById('contain');
					$.getJSON(nextPageUrl, function(data) {
						//var myData = eval('(' + data + ')');
						var myData=data;
						nextUrl = myData.nextURL;
						group(myData.photos);
						for (var timeString in newData) {
							var h3 = document.createElement('h3');
							//现实日期
							h3.innerHTML = timeString;

							var num = newData[timeString].length;
							var ul = document.createElement('ul');
							for (var i = 0; i < num; i++) {
								var img = document.createElement('img');
								var nowImg = newData[timeString][i];
								//调整图片大小 使图片宽度和高度最大160px
								if (nowImg.width > 160 && nowImg.width > nowImg.height) {
									img.width = 160;
								} else if (nowImg.height > 160) {
									img.height = 160;
								}
								img.src = nowImg.imageURL;
								//超过5个则换行
								if (i % 5 == 0 && i != 0) {
									var brtag = document.createElement('br');
									ul.appendChild(brtag);
								}
								ul.appendChild(img);
							}
							//将新建的html标签插入到容器中
							contain.appendChild(h3);
							contain.appendChild(ul);
						}
					});
				}
				//调用函数getJsonData
				getJsonData(nextUrl);
				
				window.onscroll = function() {
					if ($(window).scrollTop() + $(window).height() + 100 > $(document).height()) {
						getJsonData(nextUrl);
					}
				}
			});
		</script>
	</body>
</html>
